package com.ruicar.afs.cloud.afscase.infomanagement.controller;

import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelAffiliatedUnits;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelRiskInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelAffiliatedUnitsService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelRiskInfoService;
import com.ruicar.afs.cloud.afscase.common.service.AggregateService;
import com.ruicar.afs.cloud.afscase.common.utils.CompareFieldsUtil;
import com.ruicar.afs.cloud.afscase.common.utils.DicUtils;
import com.ruicar.afs.cloud.afscase.infomanagement.condition.CarInfoCondition;
import com.ruicar.afs.cloud.afscase.infomanagement.condition.CaseInfoQueryCondition;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.*;
import com.ruicar.afs.cloud.afscase.infomanagement.service.*;
import com.ruicar.afs.cloud.afscase.infomanagement.vo.*;
import com.ruicar.afs.cloud.aggregate.dto.ValuationDto;
import com.ruicar.afs.cloud.aggregate.dto.VinInfoDto;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import com.ruicar.afs.cloud.components.datadicsync.DicHelper;
import com.ruicar.afs.cloud.components.datadicsync.dto.DicDataDto;
import com.ruicar.afs.cloud.parameter.commom.service.TsysAddressParamService;
import com.ruicar.afs.cloud.vehicle.dto.CarInfoDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>Description: </p>
 *
 * @author jiaqi.guo
 * @version 1.0
 * @date create on 2020-05-25 18:14
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api("资产信息")
@RequestMapping("/asset")
public class CaseCarInfoController {

    private CaseBaseInfoService caseBaseInfoService;

    private CaseCarInfoService caseCarInfoService;

    private CaseCostInfoService caseCostInfoService;

    private ChannelRiskInfoService channelRiskInfoService;

    private ChannelAffiliatedUnitsService channelAffiliatedUnitsService;

    private CaseChannelInfoService caseChannelInfoService;

    private CaseCarStyleDetailService carStyleDetailInfoService;

    private ChannelBaseInfoService channelBaseInfoService;

    private TsysAddressParamService tsysAddressParamService;

    private AggregateService aggregateService;

    private CaseRedundantInfoService redundantInfoService;

    /**
     * queryAssetSummaryInfo
     * <p>Description: </p>
     *
     * @param
     * @return
     */
    @PostMapping(value = "/queryAssetSummaryInfo")
    @ApiOperation(value = "根据申请编号查询资产基本信息和挂靠信息")
    public IResponse<AssetPageInfoVo> queryAssetSummaryInfo(@ModelAttribute CaseInfoQueryCondition caseInfoQueryCondition) {

        AssetPageInfoVo assetPageInfoVo = new AssetPageInfoVo();
        boolean affixed = true;
        CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                .eq(CaseBaseInfo::getApplyNo, caseInfoQueryCondition.getApplyNo()));
        List<CaseCarInfo> list = caseCarInfoService.list(Wrappers.<CaseCarInfo>lambdaQuery()
                .eq(CaseCarInfo::getApplyNo,caseInfoQueryCondition.getApplyNo()));
        if (CollectionUtils.isNotEmpty(list)) {
            CaseCarInfo caseCarInfo = list.get(0);
            assetPageInfoVo.setCooperPlat(caseCarInfo.getCooperPlat());

            CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
                    .eq(CaseChannelInfo::getApplyNo, caseInfoQueryCondition.getApplyNo()));

            /**  封装响应数据  **/
            if (ObjectUtils.isNotEmpty(caseBaseInfo) && ObjectUtils.isNotEmpty(caseCarInfo) && ObjectUtils.isNotEmpty(caseChannelInfo)) {

                assetPageInfoVo.setAffiliatedWay(caseBaseInfo.getAffiliatedWay());
                assetPageInfoVo.setSaleAdvisor(caseChannelInfo.getSaleAdvisor());
                assetPageInfoVo.setSaleAdvisorPhone(caseChannelInfo.getSalePhone());
                ChannelBaseInfo channelInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda()
                        .eq(ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo())
                );
                if (ObjectUtils.isNotEmpty(channelInfo)) {
                    String province = tsysAddressParamService.getProvinceOrCtiy(channelInfo.getChannelProvince()) != null ? tsysAddressParamService.getProvinceOrCtiy(channelInfo.getChannelProvince()).getLabel() : "";
                    String city = tsysAddressParamService.getProvinceOrCtiy(channelInfo.getChannelCity()) != null ? tsysAddressParamService.getProvinceOrCtiy(channelInfo.getChannelCity()).getLabel() : "";
                    assetPageInfoVo.setChannelAddress(province + city);
                    assetPageInfoVo.setChannelFullName(channelInfo.getChannelFullName());
                    /**渠道归属*/
                    assetPageInfoVo.setChannelBelong(channelInfo.getChannelBelong());
                }


                if (AffiliatedWayEnum.NO.getCode().equals(caseBaseInfo.getAffiliatedWay())) {
                    affixed = false;
                }
                ChannelAffiliatedUnits channelAffiliatedUnits=new ChannelAffiliatedUnits();
                if(StringUtils.isNotBlank(caseCarInfo.getAffCompanyId())){
                    /**  挂靠单位信息  **/
                    channelAffiliatedUnits = channelAffiliatedUnitsService.getOne(Wrappers.<ChannelAffiliatedUnits>query().lambda()
                            .eq(ChannelAffiliatedUnits::getId, Long.parseLong(caseCarInfo.getAffCompanyId())));

                }
                if (AfsEnumUtil.key(AffiliatedWayEnum.PERSONAL_AFFILIATED).equals(caseBaseInfo.getAffiliatedWay())) {
                    channelAffiliatedUnits.setAffiliatedName(caseCarInfo.getIndBusinessName());
                }
                assetPageInfoVo.setAffiliateInfo(channelAffiliatedUnits);
                if (ObjectUtils.isNotEmpty(channelInfo)) {
                    if (channelInfo.getChannelBelong().equals(AfsEnumUtil.key(ChannelBelongEnum.DIRECT))) {
                        ChannelRiskInfo channelRiskInfo = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfo>query().lambda()
                                .eq(ChannelRiskInfo::getChannelId, caseChannelInfo.getCarDealersId())
                                .eq(ChannelRiskInfo::getBusinessType, caseBaseInfo.getBusinessType()));
                        if (ObjectUtils.isNotEmpty(channelRiskInfo)) {
                            assetPageInfoVo.setChannelGrade(channelRiskInfo.getChannelGrade());
                            assetPageInfoVo.setQualityGrade(channelRiskInfo.getQualityGrade());
                        }
                    } else {
                        ChannelRiskInfo channelRiskInfo = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfo>query().lambda()
                                .eq(ChannelRiskInfo::getChannelId, channelInfo.getChannelId())
                                .eq(ChannelRiskInfo::getBusinessType, caseBaseInfo.getBusinessType()));
                        if (ObjectUtils.isNotEmpty(channelRiskInfo)) {
                            assetPageInfoVo.setChannelGrade(channelRiskInfo.getChannelGrade());
                            assetPageInfoVo.setQualityGrade(channelRiskInfo.getQualityGrade());
                        }
                    }

                }
            } else {
                assetPageInfoVo.setAffiliateInfo(new ChannelAffiliatedUnits());
            }
        }

        assetPageInfoVo.setAffixed(affixed);
        return IResponse.success(assetPageInfoVo);
    }

    /**
     * queryCarSummaryInfo
     * <p>Description: </p>
     *
     * @param
     * @return
     */
    @PostMapping(value = "/queryCarSummaryInfo")
    @ApiOperation(value = "根据判断新车二手车挂牌车")
    public IResponse<CarSummaryInfoVo> queryCarSummaryInfo(@ModelAttribute CaseInfoQueryCondition caseInfoQueryCondition) {

        CarSummaryInfoVo carSummaryInfoVo = new CarSummaryInfoVo();
        boolean pageOne = false;
        boolean pageTwo = false;
        boolean pageThree = false;

        CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                .eq(CaseBaseInfo::getApplyNo, caseInfoQueryCondition.getApplyNo()));
        /**  封装响应数据  **/
        if (ObjectUtils.isNotEmpty(caseBaseInfo)) {
            if (BusinessTypeEnum.NEW_CAR.getCode().equals(caseBaseInfo.getBusinessType())
                    && AfsEnumUtil.key(CarNatureEnum.NEW_CAR).equals(caseBaseInfo.getCarNature())) {
                pageOne = true;
            } else if (BusinessTypeEnum.OLD_CAR.getCode().equals(caseBaseInfo.getBusinessType())) {
                pageTwo = true;
            } else if (BusinessTypeEnum.NEW_CAR.getCode().equals(caseBaseInfo.getBusinessType())
                    && AfsEnumUtil.key(CarNatureEnum.PLATE_CAR).equals(caseBaseInfo.getCarNature())) {
                pageThree = true;
            }
        }
        Console.log(pageOne);
        carSummaryInfoVo.setPageOne(pageOne);
        carSummaryInfoVo.setPageTwo(pageTwo);
        carSummaryInfoVo.setPageThree(pageThree);
        return IResponse.success(carSummaryInfoVo);
    }

    /**
     * queryCarDetailInfo
     * <p>Description: </p>
     *
     * @param
     * @return
     */
    @PostMapping(value = "/queryCarDetailInfo")
    @ApiOperation(value = "根据申请编号查询车辆详细信息")
    public IResponse<CarInfoVo> queryCarDetailInfo(@ModelAttribute CaseInfoQueryCondition caseInfoQueryCondition) {

        CarInfoVo carInfoVo = new CarInfoVo();

        List<CaseCarInfo> caseCarInfoList = caseCarInfoService.list(Wrappers.<CaseCarInfo>query().lambda()
                .eq(CaseCarInfo::getApplyNo, caseInfoQueryCondition.getApplyNo()));

        //查询常规审批案件是否出结果
        CaseBaseInfo info = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>lambdaQuery()
                .eq(CaseBaseInfo::getApplyNo,caseInfoQueryCondition.getApplyNo()));
        if (ObjectUtils.isEmpty(info)) {
            info = new CaseBaseInfo();
        }
        BusinessStateInEnum caseStatusEnum = Objects.isNull(info.getBusinessStateIn())
                ? null
                : (BusinessStateInEnum) AfsEnumUtil.getEnum(info.getBusinessStateIn(),BusinessStateInEnum.class);
        Set<BusinessStateInEnum> resultBusinessStatus = new HashSet<>();
        resultBusinessStatus.add(BusinessStateInEnum.REPEAL);
        resultBusinessStatus.add(BusinessStateInEnum.REJECT);
        resultBusinessStatus.add(BusinessStateInEnum.APPROVED);
        resultBusinessStatus.add(BusinessStateInEnum.CONDITIONAL_APPROVE);
        resultBusinessStatus.add(BusinessStateInEnum.CANCEL_ADVICE_CONDITIONAL);
        carInfoVo.setCaseFlag(!resultBusinessStatus.contains(caseStatusEnum));

        /**  封装响应数据  **/
        if (ObjectUtils.isNotEmpty(caseCarInfoList)) {
            BeanUtils.copyProperties(caseCarInfoList.get(0), carInfoVo);
            if(ObjectUtils.isEmpty(carInfoVo.getLoanAmtMax())){
                carInfoVo.setLoanAmtMax(BigDecimal.ZERO);
            }
            carInfoVo.setCarId(caseCarInfoList.get(0).getId().toString());

            CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                    .eq(CaseBaseInfo::getApplyNo, caseCarInfoList.get(0).getApplyNo()));

            CaseCarStyleDetail caseCarStyleDetail = carStyleDetailInfoService.getOne(Wrappers.<CaseCarStyleDetail>query().lambda()
                    .eq(CaseCarStyleDetail::getCarId, caseCarInfoList.get(0).getId()));
            //车辆销售价格
            BigDecimal carPrice = caseCarInfoList.get(0).getSalePrice();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String strDate = format.format(new Date());
            //截止日期
            String deadline = this.getDeadline();

            //非新能源乘用车 "我司车价预警值"
            String modelCode = caseCarInfoList.get(0).getModelCode();
            String cityInfo = caseCarInfoList.get(0).getPurchaseCity();
            String provinceInfo = caseCarInfoList.get(0).getPurchaseProvince();
            //业务状态（内）
            List statusList = new ArrayList();
            statusList.add(AfsEnumUtil.key(BusinessStateInEnum.APPROVED));
            statusList.add(AfsEnumUtil.key(BusinessStateInEnum.CONDITIONAL_APPROVE));
            statusList.add(AfsEnumUtil.key(BusinessStateInEnum.REJECT));
            statusList.add(AfsEnumUtil.key(BusinessStateInEnum.REPEAL));
            statusList.add(AfsEnumUtil.key(BusinessStateInEnum.CANCEL_ADVICE_CONDITIONAL));
            CaseBaseInfo baseInfo=caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                    .eq(CaseBaseInfo::getApplyNo, caseInfoQueryCondition.getApplyNo()));
            CaseCarInfo carBaseInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda()
                    .eq(CaseCarInfo::getId, caseCarInfoList.get(0).getId()));
            /**未出结果的案件实时统计*/
            if(!statusList.contains(baseInfo.getBusinessStateIn())) {
                if (ObjectUtils.isNotEmpty(caseCarStyleDetail)) {
                    if (AfsEnumUtil.key(WhetherEnum.NO).equals(caseCarStyleDetail.getIsGreen())
                            && CarTypeEnum.PASSENGER_CAR.getCode().equals(caseBaseInfo.getCarType())) {
                        BigDecimal priceWarn = this.queryPriceWarnInfo(
                                modelCode,
                                cityInfo,
                                provinceInfo,
                                strDate,
                                deadline,
                                carPrice);
                        if (priceWarn != null) {
                            carInfoVo.setPriceWarn(priceWarn);
                            carBaseInfo.setPriceWarn(priceWarn);
                        }
                    }
                }
                //LCV "我司车价预警值"
                if (CarTypeEnum.LCV.getCode().equals(caseBaseInfo.getCarType())) {
                    BigDecimal priceWarn = this.queryPriceWarnInfo(
                            modelCode,
                            cityInfo,
                            provinceInfo,
                            strDate,
                            deadline,
                            carPrice);
                    if (priceWarn != null) {
                        carInfoVo.setPriceWarn(priceWarn);
                        carBaseInfo.setPriceWarn(priceWarn);
                    }
                }
                caseCarInfoService.updateById(carBaseInfo);
            }else{
                carInfoVo.setPriceWarn(carBaseInfo.getPriceWarn());

            }
            /**  购车目的  **/
            if (ObjectUtils.isNotEmpty(caseBaseInfo)) {
                carInfoVo.setCarPurpose(caseBaseInfo.getCarPurpose());
            }
            /**购车地址*/
            String purchaseProvince = tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getPurchaseProvince()) != null ? tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getPurchaseProvince()).getLabel() : "";
            String purchaseCity = tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getPurchaseCity()) != null ? tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getPurchaseCity()).getLabel() : "";
            carInfoVo.setPurchaseAddress(purchaseProvince + purchaseCity);
            /**车身类型*/
            carInfoVo.setCarBodyClass(caseCarInfoList.get(0).getCarBodyClass());
            /**  上牌地  **/
            String province = tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getLicenseProvince()) != null ? tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getLicenseProvince()).getLabel() : "";
            String city = tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getLicenseCity()) != null ? tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getLicenseCity()).getLabel() : "";
            carInfoVo.setPlateAddress(province + city);

            /**  注册地  **/
            String registProvince = tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getRegistProvince()) != null ? tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getRegistProvince()).getLabel() : "";
            String registCity = tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getRegistCity()) != null ? tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getRegistCity()).getLabel() : "";
            carInfoVo.setRegistAddress(registProvince + registCity);

            /**车商联系地址*/
            String carDealerProvince = tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getRegistProvince()) != null ? tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getCarDealerProvince()).getLabel() : "";
            String carDealerCity = tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getRegistCity()) != null ? tsysAddressParamService.getProvinceOrCtiy(caseCarInfoList.get(0).getCarDealerCity()).getLabel() : "";
            carInfoVo.setCarDealerAddress(carDealerProvince+carDealerCity);
            CarWarningInfoVo warningInfo = new CarWarningInfoVo();
            if (ObjectUtils.isNotEmpty(caseBaseInfo)) {
                //二手车/挂牌
                /**---------------------------历史VIN号------------------------------ **/

                CarVinInfoEntity vin = new CarVinInfoEntity();
                //车架号
                List<VinInfoDto> list = aggregateService.getUsedcarHis(caseCarInfoList.get(0).getCarVin(), caseInfoQueryCondition.getApplyNo());
                vin.setShowflag(false);
                if (CollectionUtils.isNotEmpty(list)) {
                    vin.setTitle("历史VIN号(" + list.size() + ")");
                    vin.setShowflag(true);
                }
                vin.setMsgs(list);
                warningInfo.setVin(vin);
                /**---------------------------车辆预警------------------------------ **/

                CarWarningEntity car = new CarWarningEntity();
                List<String> msgs2 = new ArrayList<>();
                CarInfoDto carInfoDto = new CarInfoDto();
                //城市
                carInfoDto.setZoneId(caseCarInfoList.get(0).getPurchaseCity());
                //车型
                carInfoDto.setModelId(caseCarStyleDetail.getCarModelId());
                //销售价格
                carInfoDto.setLastPrice(caseCarInfoList.get(0).getSalePrice());
                Date date = new Date();
                carInfoDto.setVersion(Long.valueOf(date.getTime()));
                String url = aggregateService.getPriceUrl(carInfoDto);
                msgs2.add(url);
                car.setShowflag(false);
                car.setTitle("车辆预警信息");
                car.setMsgs(msgs2);
                warningInfo.setCar(car);

                /**---------------------------评估报告对比------------------------------ **/
                CarInfoDto carInfo = new CarInfoDto();
                carInfo.setVin(caseCarInfoList.get(0).getCarVin());
                carInfo.setStartDate((new Date()).getTime());
                carInfo.setEndDate((new Date()).getTime());
                /**车e估最新结果*/
                ValuationDto oldValuationDto = aggregateService.getValuationReport(carInfo);
                /**业务数据信息*/
                ValuationDto newValuationDto = new ValuationDto();
                newValuationDto.setVin(caseCarInfoList.get(0).getCarVin());
                //所有人
                newValuationDto.setOwnerName(caseCarInfoList.get(0).getCarBelongs());
                //使用性质
                Map<String, List<DicDataDto>> carFunctionMap = DicHelper.getDicMaps("carFunction");
                newValuationDto.setCarUsetype(DicUtils.translate(caseCarInfoList.get(0).getCarFunction(), carFunctionMap));
                //车牌号
                newValuationDto.setGBNo(caseCarInfoList.get(0).getLicensePlate());
                //总过户次数
                newValuationDto.setCarTransferNumber(String.valueOf(caseCarInfoList.get(0).getTransNums()));
                //发动机号
                newValuationDto.setEngineNo(caseCarInfoList.get(0).getEngineNo());
                //首次登陆日期
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
                newValuationDto.setRegDate(caseCarInfoList.get(0).getFirstLandingDate() != null ? dateFormat.format(caseCarInfoList.get(0).getFirstLandingDate()) : "");

                /**两者对比*/
                String keyStr = "";
                String accidenttype = "";

                if (ObjectUtils.isNotEmpty(oldValuationDto)) {
                    keyStr = CompareFieldsUtil.compareFields(oldValuationDto, newValuationDto);
                    /**事故类型*/
                    accidenttype = oldValuationDto.getAccidenttype();
                }
                String strInfo = "";

                if (StringUtils.isNotBlank(keyStr)) {
                    String[] keys = keyStr.split(",");
                    for (int i = 0; i < keys.length; i++) {
                        if ("vin".equals(keys[i])) {
                            strInfo += "车架号 ";
                        } else if ("ownerName".equals(keys[i])) {
                            strInfo += "所有人  ";
                        } else if ("carUsetype".equals(keys[i])) {
                            strInfo += "使用性质 ";
                        } else if ("GBNo".equals(keys[i])) {
                            strInfo += "车牌号 ";
                        } else if ("carTransferNumber".equals(keys[i])) {
                            strInfo += "总过户次数 ";
                        } else if ("engineNo".equals(keys[i])) {
                            strInfo += "发动机号 ";
                        } else if ("regDate".equals(keys[i])) {
                            strInfo += "首次登记日期 ";
                        }
                    }
                }
                log.info("对比输出" + strInfo);
                CarWarningEntity price = new CarWarningEntity();
                List<String> msgs3 = new ArrayList<>();
                /**如果对比字段不一致或存在事故车/水泡车/调表车/火烧车*/
                log.info("事故车字段返回结果：" + accidenttype);
                if (StringUtils.isNotBlank(strInfo)) {//不一致
                    msgs3.add(strInfo);
                    price.setMsgs(msgs3);
                    price.setShowflag(false);
                    price.setTitle("估值报告比对信息");
                    price.setAccidenttyp(accidenttype != null ? accidenttype : "");
                    price.setFlag(WhetherEnum.NO.getCode());
                    price.setDescribe("以下进件字段与估值报告不一致");
                    warningInfo.setPrice(price);
                } else {//一致
                    msgs3.add(strInfo);
                    price.setMsgs(msgs3);
                    price.setAccidenttyp(accidenttype != null ? accidenttype : "");
                    price.setShowflag(false);
                    price.setTitle("估值报告比对信息");
                    price.setFlag(WhetherEnum.YES.getCode());
                    price.setDescribe("进件字段与估值报告一致");
                    warningInfo.setPrice(price);
                }
                carInfoVo.setWarningInfo(warningInfo);
            }
            List list = this.getEvidenceCaseCarInfo(caseInfoQueryCondition.getApplyNo());
            if (CollectionUtils.isNotEmpty(list)) {
                RedundantSignVo signVo = JSONObject.parseObject(JSONObject.toJSONString(list.get(0)), RedundantSignVo.class);
                CaseCarInfo caseCarInfo = JSONObject.parseObject(JSONObject.toJSONString(list.get(1)), CaseCarInfo.class);
                if (ObjectUtils.isNotEmpty(caseCarInfo)) {
                    carInfoVo.setModelNameOld(caseCarInfo.getModelName());
                    carInfoVo.setStyleNameOld(caseCarInfo.getStyleName());
                }
                carInfoVo.setBackSign(signVo.getBackSign());
                carInfoVo.setReconsiderSign(signVo.getReconsiderSign());
            }
        }
        return IResponse.success(carInfoVo);
    }
    /**
     * saveAddress
     * <p>Description: 更新新车车辆信息</p>
     * @param
     * @return
     */
    @PostMapping(value = "/saveNewCarInfo")
    @ApiOperation(value = "更新新车车辆信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<String> saveNewCarInfo(@ModelAttribute CarInfoVo carInfoVo) {
        if (ObjectUtils.isNotEmpty(carInfoVo)) {
            CaseCarInfo caseCarInfo = caseCarInfoService.getById(Long.parseLong(carInfoVo.getCarId()));
            caseCarInfo.setLicenseProvince(carInfoVo.getLicenseProvince());
            caseCarInfo.setLicenseCity(carInfoVo.getLicenseCity());
            caseCarInfo.setFirmPrice(carInfoVo.getFirmPrice());
            caseCarInfoService.updateById(caseCarInfo);
            return IResponse.success("更新车辆信息信息成功");
        }
        return IResponse.fail("车辆信息为空");
    }

    /**
     * saveAddress
     * <p>Description: 更新新车车辆信息</p>
     * @param
     * @return
     */
    @PostMapping(value = "/saveOldCarInfo")
    @ApiOperation(value = "更新二手车车车辆信息")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<String> saveOldCarInfo(@ModelAttribute CarInfoVo carInfoVo) {
        if (ObjectUtils.isNotEmpty(carInfoVo)) {
            CaseCarInfo caseCarInfo = caseCarInfoService.getById(Long.parseLong(carInfoVo.getCarId()));
            caseCarInfo.setLicenseProvince(carInfoVo.getLicenseProvince());
            caseCarInfo.setLicenseCity(carInfoVo.getLicenseCity());
            caseCarInfo.setEvaluatingPrice(carInfoVo.getEvaluatingPrice());
            caseCarInfoService.updateById(caseCarInfo);
            return IResponse.success("更新车辆信息信息成功");
        }
        return IResponse.fail("车辆信息为空");
    }
    /**
     * @description: 获取冗余数据
     * @created 2020/08/31 16:07
     * @version 1.0
     */
    public List getEvidenceCaseCarInfo(String applyNo) {

        RedundantSignVo signVo = new RedundantSignVo();
        signVo.setBackSign(WhetherEnum.NO.getCode());
        signVo.setReconsiderSign(WhetherEnum.NO.getCode());
        CaseCarInfo caseCarInfo = null;
        List list = new ArrayList();
        CaseRedundantInfo redundantInfo = redundantInfoService.getOne(Wrappers.<CaseRedundantInfo>query().lambda()
                .eq(StringUtils.isNotBlank(applyNo), CaseRedundantInfo::getApplyNo, applyNo));
        if (ObjectUtils.isNotEmpty(redundantInfo)) {
            String backSign = redundantInfo.getBackSign();
            if (WhetherEnum.YES.getCode().equals(backSign)) {
                String backEvidence = redundantInfo.getBackEvidence();
                if (StringUtils.isNotBlank(backEvidence)) {
                    caseCarInfo = this.getEvidenceForCarInfo(backEvidence);
                    signVo.setBackSign(WhetherEnum.YES.getCode());
                    signVo.setReconsiderSign(WhetherEnum.NO.getCode());
                }
            }
            String reconsiderSign = redundantInfo.getReconsiderSign();
            if (WhetherEnum.YES.getCode().equals(reconsiderSign)) {
                String reconsiderEvidence = redundantInfo.getReconsiderEvidence();
                if (StringUtils.isNotBlank(reconsiderEvidence)) {
                    caseCarInfo = this.getEvidenceForCarInfo(reconsiderEvidence);
                    signVo.setBackSign(WhetherEnum.NO.getCode());
                    signVo.setReconsiderSign(WhetherEnum.YES.getCode());
                }
            }
        }
        list.add(signVo);
        list.add(caseCarInfo);
        return list;
    }

    /**
     * @description: 解析车辆信息详情冗余数据
     * @created 2020/8/31 20:27
     * @version 1.0
     */
    public CaseCarInfo getEvidenceForCarInfo(String jsonStr) {
        CaseCarInfo caseCarInfo = new CaseCarInfo();
        if (StringUtils.isNotBlank(jsonStr)) {
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            JSONArray carInfo = jsonObject.getJSONArray("carInfoList");
            if (ObjectUtils.isNotEmpty(carInfo) && carInfo.size() > 0) {
                BeanUtils.copyProperties(carInfo.toJavaList(CaseCarInfo.class).get(0), caseCarInfo);
            }
        }
        return caseCarInfo;
    }

    /**
     * queryCarStyleDetailInfo
     * <p>Description: 根据车辆id查询车辆配型信息</p>
     *
     * @param
     * @return
     */
    @PostMapping(value = "/queryCarStyleDetailInfo")
    @ApiOperation(value = "根据车辆id查询车辆配型信息")
    public IResponse<CarCarStyleDetailInfoVo> queryCarStyleDetailInfo(@ModelAttribute CaseInfoQueryCondition caseInfoQueryCondition) {

        CarCarStyleDetailInfoVo carStyleDetailInfoVo = new CarCarStyleDetailInfoVo();
        log.info("车辆参数获取carId:{}", caseInfoQueryCondition.getCarId());
        CaseCarStyleDetail caseCarStyleDetail = carStyleDetailInfoService.getOne(Wrappers.<CaseCarStyleDetail>query().lambda()
                .eq(CaseCarStyleDetail::getCarId, Long.parseLong(caseInfoQueryCondition.getCarId())));

        if (ObjectUtils.isNotEmpty(caseCarStyleDetail)) {
            BeanUtils.copyProperties(caseCarStyleDetail, carStyleDetailInfoVo);
        }

        return IResponse.success(carStyleDetailInfoVo);
    }

    /**
     * <p>Description: </p>
     *
     * @param
     * @return
     */
    @PostMapping(value = "/claculateLoanAmtMax")
    @ApiOperation(value = "计算最大贷款限额")
    public IResponse<CalculateResultVo> claculateLoanAmtMax(@ModelAttribute CaseInfoQueryCondition caseInfoQueryCondition) {

        CalculateResultVo calculateResultVo = new CalculateResultVo();

        /**  此处调用需要调用产品服务的计算接口，具体需要参数可以从前台获取，也可以按照车辆id和申请编号从数据库查询  **/
        BigDecimal loanAmtMax = caseCarInfoService.calculateLoanAmtMaxByCar(caseInfoQueryCondition);

        if (ObjectUtils.isNotEmpty(loanAmtMax)) {
            calculateResultVo.setLoanAmtMax(loanAmtMax);
            return IResponse.success(calculateResultVo);
        } else {
            throw new AfsBaseException("计算失败，请重试");
        }

    }

    /**
     * @description: 获取当前日期 前90天时间
     * @author jiaqi.guo
     * @created 2020/9/1 18:08
     * @version 1.0
     */
    public String getDeadline() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -90);
        Date time = c.getTime();
        String preDay = sdf.format(time);
        return preDay;
    }
    /**
     * @description: 获取我司车价预警值
     * @author jiaqi.guo
     * @created 2020/9/1 20:54
     * @version 1.0
     */
    public BigDecimal queryPriceWarnInfo(String modelCode,
                                     String purchaseCity,
                                     String purchaseProvince,
                                     String strDate,
                                     String deadline,
                                     BigDecimal salePrice ) {
        CarInfoCondition condition = new CarInfoCondition();
        //车型
        condition.setModelCode(modelCode);
        condition.setStrDate(strDate);
        condition.setDeadline(deadline);
        /**城市 大于10笔*/
        condition.setPurchaseCity(purchaseCity);
        List<CaseCarInfo> carListCity = caseCarInfoService.getAllCarInfo(condition);
        if (CollectionUtils.isNotEmpty(carListCity) && carListCity.size() > 10) {
            BigDecimal p90=this.returNp90Data(carListCity);
            //车辆销售价大于p90
            if(p90.compareTo(salePrice)==-1){
                return p90;
            }else{
                return null;
            }
        }else{
            condition.setPurchaseCity(null);
        }
        /**省份 大于10笔*/
        condition.setPurchaseProvince(purchaseProvince);
        List<CaseCarInfo> carListProvince = caseCarInfoService.getAllCarInfo(condition);
        if (CollectionUtils.isNotEmpty(carListProvince) && carListProvince.size() > 10) {
            BigDecimal p90=this.returNp90Data(carListProvince);
            //车辆销售价大于p90
            if(p90.compareTo(salePrice)==-1){
                return p90;
            }else{
                return null;
            }
        }else{
            condition.setPurchaseProvince(null);
        }
        /**全国 大于10笔*/
        List<CaseCarInfo> carListAll = caseCarInfoService.getAllCarInfo(condition);
        if (CollectionUtils.isNotEmpty(carListAll) && carListAll.size() > 10) {
            BigDecimal p90=this.returNp90Data(carListAll);
            //车辆销售价大于p90
            if(p90.compareTo(salePrice)==-1){
                return p90;
            }else{
                return null;
            }
        }

        /**城市 大于1小于等于10笔*/
        condition.setPurchaseCity(purchaseCity);
        List<CaseCarInfo> carListCitySmall = caseCarInfoService.getAllCarInfo(condition);
        if (CollectionUtils.isNotEmpty(carListCitySmall) && carListCitySmall.size()<= 10) {
            BigDecimal maxPrice=this.returBigValue(carListCitySmall);
            //车辆销售价大于p90
            if(maxPrice.compareTo(salePrice)==-1){
                return maxPrice;
            }else{
                return null;
            }
        }else{
            condition.setPurchaseCity(null);
        }
        /**省份 大于1小于等于10笔*/
        condition.setPurchaseProvince(purchaseProvince);
        List<CaseCarInfo> carListProvinceSmall = caseCarInfoService.getAllCarInfo(condition);
        if (CollectionUtils.isNotEmpty(carListProvinceSmall) && carListProvinceSmall.size() <= 10) {
            BigDecimal maxPrice=this.returBigValue(carListProvinceSmall);
            //车辆销售价大于p90
            if(maxPrice.compareTo(salePrice)==-1){
                return maxPrice;
            }else{
                return null;
            }
        }else{
            condition.setPurchaseProvince(null);
        }
        /**全国 大于1小于等于10笔*/
        List<CaseCarInfo> carListAllSmall = caseCarInfoService.getAllCarInfo(condition);
        if (CollectionUtils.isNotEmpty(carListAllSmall) && carListAllSmall.size() <= 10) {
            BigDecimal maxPrice=this.returBigValue(carListAllSmall);
            //车辆销售价大于p90
            if(maxPrice.compareTo(salePrice)==-1){
                return maxPrice;
            }else{
                return null;
            }
        }
        return null;
    }
    /**
     * @description: 根据不同场景获取p90的值 大于10笔
     * @author jiaqi.guo
     * @created 2020/9/1 19:46
     * @version 1.0
     */
    public BigDecimal returNp90Data(List<CaseCarInfo> list){
        BigDecimal p90=BigDecimal.ZERO;
        double N=list.size()*0.9;
        double eps = 1e-10;
        boolean isInteger = N - Math.floor(N) < eps;
        //当结果不包含小数位时（值为 M），取第 M 个第 M+1 个数的和再除以 2 作为 P90 值
        if(isInteger){
             p90=(list.get((int)N-1).getSalePrice().add(list.get((int)N).getSalePrice())).divide(new BigDecimal(2));
        }else{//3.当 N*0.9 的结果包含小数位时，对结果向上取整，得到 M，取第 M 个价格作为 P90 值
            double M = Math.ceil(N);
            p90=p90.add(list.get((int)M-1).getSalePrice());
        }
        return p90;
    }
    /**
     * @description: 根据不同场景获取最大值 大于10笔
     * @author jiaqi.guo
     * @created 2020/9/1 19:46
     * @version 1.0
     */
    public BigDecimal returBigValue(List<CaseCarInfo> list) {

        //获取maxPriceList列表取最大值
        List<BigDecimal> maxPriceList = list.stream().map(CaseCarInfo::getSalePrice).collect(Collectors.toList());
        BigDecimal maxPrice = Collections.max(maxPriceList);
        return maxPrice;
    }
}
